/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.crt.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.seari.bean.crt.CRTDataBean;
import com.seari.utils.DataUtil;

/**
 *
 * @author yyw
 */
public class CRTDecoder extends ByteToMessageDecoder {
	protected static Logger logger = LoggerFactory.getLogger(CRTDecoder.class);

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		
		// byteBuf转成String
		byte[] bytes = new byte[in.readableBytes()];                
		in.readBytes(bytes);
                String msg2 = DataUtil.BytesToHexStr(bytes);
                System.out.println("receive msg :" + msg2);
		msg2= msg2.replace(" ", "");
		StringBuilder sb = new StringBuilder(msg2);
//		// 厂家将消息中“0020”改为“20”发送，需在转回“0020”再转成String
//		for (int i = 0; i <= (sb.length()) / 4 && (i * 4) != sb.length(); i++) {
//			int x = (i * 4);
//			if (sb.substring(x, x + 2).equals("20")) {
//				sb.replace(x, x + 2, "0020");
//			}
//		}
		String result = unicode2String(CRTmsg2unicode(msg2));
		logger.info("CRTdecode >>>：" + result);
        System.out.println("长度>>>>>>>>>>>>>："+result.length());
		CRTDataBean bean = new CRTDataBean();
		bean.setStatus(result.substring(0, 40).replace(" ", ""));
		bean.setDevice(del(result.substring(40, 80).replace(" ", "")));
		bean.setArea(del(result.substring(80, 107).replace(" ", "")));
		bean.setType(result.substring(107, 120).replace(" ", ""));
		Date date = null;
		if (result.substring(130, 131).equals("A")) {
			// 12小时制 上午
			String str = result.substring(122, 130) + result.substring(131, 149).replace(",", "");
			date = new Date(str);
		} else if (result.substring(130, 131).equals("P")) {
			// 12小时制 下午 +12个小时
			String str = Integer.parseInt(result.substring(122, 124)) + 12 + result.substring(124, 130)
					+ result.substring(131, 149).replace(",", "");
			date = new Date(str);
			System.out.println(date);
		}
		
		bean.setTime(date);
		bean.setDsNum(result.substring(149, 162).replace(" ", ""));
		out.add(bean);
	}

	/**
	 * 将CRT协议传来的信息转成unicode字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String CRTmsg2unicode(String str) {
		str = str.replace(" ", "");
		StringBuilder sb = new StringBuilder(str);
		for (int i = 0; i < sb.length(); i = i + 6) {
			sb.insert(i, "\\u");
		}
		return sb.toString();
	}

	/**
	 * 将unicode字符串转成String
	 * 
	 * @param unicode
	 * @return
	 */
	public static String unicode2String(String unicode) {
		StringBuffer str = new StringBuffer();
		String[] hex = unicode.split("\\\\u");
		for (int i = 1; i < hex.length; i++) {
			// 转换出每一个代码点
			int data = Integer.parseInt(hex[i], 16);
			// 追加成string
			str.append((char) data);
		}
		return String.valueOf(str);
	}

	/**
	 * 去除字符串中的中文
	 * 
	 * @param str
	 * @return
	 */
	public String del(String str) {
		String regexChinese = "[\u4e00-\u9fa5]";// 中文正则
		Pattern pat = Pattern.compile(regexChinese);
		Matcher mat = pat.matcher(str);
		return mat.replaceAll("");
	}
}
